package cn.ven.controller;

import cn.ven.entity.*;
import cn.ven.service.*;
import cn.ven.tool.RespJson;
import cn.ven.tool.Token;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
   不需要登录就可以访问
   谁都可以访问
 */
@Controller
@RequestMapping("/api/public")
public class PublicController {
    private static Logger logger= LoggerFactory.getLogger(PublicController.class);

    @Autowired
    HotService hotService;

    @Autowired
    BookService bookService;

    @Autowired
    UserService userService;

    @Autowired
    LargeFileService largeFileService;

    @Autowired
    CartService cartService;

    @Autowired
    BookTypeService bookTypeService;


    //根据类型查找对应热图
    @RequestMapping("/findHot/{num}/{type}")
    @ResponseBody
    public Map<String,Object> findHot(@PathVariable("num")Integer num,
                                      @PathVariable("type")Integer type){
        logger.info("num==="+num);
        logger.info("type==="+type);
        List<Hot> hots = hotService.findByType(type, num);
        return RespJson.pack(200,"",hots);
    }

    //书本模糊查询
    //根据书名，出版社，以及作者进行模糊查询
    @RequestMapping("/findIf/{start}/{num}")
    @ResponseBody
    public Map<String,Object> findIf(@PathVariable("start")Integer start,
                                     @PathVariable("num")Integer num,
                                     String key){
        Map<String,Object> map =new HashMap<>(); //使用map去进行模糊查询
        map.put("start",start-1);
        map.put("num",num);
        map.put("key",key);
        List<Book> books = bookService.findIf(map);//模糊查询
        int total = bookService.getCountIf(key);//模糊查询总条数
        Map<String,Object> map1 =new HashMap<>();//返回给前端的数据
        map1.put("total",total);
        map1.put("books",books);
        return RespJson.pack(200,"",map1);
    }

    //注册用户
    @RequestMapping("/addUser")
    @ResponseBody
    public Map<String,Object> addUser(MyUser myUser,
                                      @RequestParam(value = "pic",required = false)MultipartFile file)throws Exception{
        String id = largeFileService.add(file);//图片id  id==null,表示没有图片上传
        myUser.setImg(id);//与user绑定
        myUser.setClosed(1);//默认解冻，可以用
        myUser.setRole("P");//角色默认买家P
        userService.addUser(myUser);//添加用户
        return RespJson.pack(200,"注册成功",null);
    }

    //根据书本类型进行分页查询
    @RequestMapping("/findBookByPage/{start}/{num}/{typeid}")
    @ResponseBody
    public Map<String,Object> findBookByPage(@PathVariable("start")Integer start,
                                             @PathVariable("num")Integer num,
                                             @PathVariable("typeid")Integer typeid){
        Map<String,Object> pageMap= new HashMap<>();//用于查询的集合
        pageMap.put("start",start-1);
        pageMap.put("num",num);
        pageMap.put("typeid",typeid);//类型id
        List<Book> books = bookService.findByPage(pageMap);
        int total = bookService.getCount(typeid);//查询结果条数
        Map<String,Object> map =new HashMap<>();//返回给前端的数据
        map.put("books",books);
        map.put("total",total);
        return RespJson.pack(200,"",map);
    }

    //显示图片
    @RequestMapping("/show/{id}")
    public  void show(HttpServletResponse response,
                      @PathVariable("id") String id){
        if (id==null){//判断id是否为空
            return;
        }
        try {
            Largefile largeFile = largeFileService.findById(id);//把b.getPicture与picture.uuid关联起来，进行图片查询
            byte[] buf=(byte[]) largeFile.getContent();//向下转型
            response.setContentType("image/jpeg");//设置图片的格式
            FileCopyUtils.copy(buf, response.getOutputStream()); //复制到网页进行输出
        }catch (Exception e){
            logger.error(String.valueOf(e));
        }
    }

    //添加书本到购物车里面
    @RequestMapping("/addCart/{bookid}")
    @ResponseBody
    public Map<String,Object> addCart(@PathVariable("bookid")Integer bookid){
        Object account = Token.getAccount();//获取token
        if (account instanceof MyUser==false){  //当token不是MyUser类型的时候，认为它就是没登录
            return RespJson.pack(401,"尚未登录，请先登录",null);
        }
        //登录的时候
        Cart cart =new Cart();
        cart.setBookid(bookid);
        cartService.addCart(cart);
        return RespJson.pack(200,"添加成功",null);
    }

    //查找所有的书本类型
    @RequestMapping("/type/findAllType")
    @ResponseBody
    public Map<String,Object> findAllType(){
        List<BookType> bookTypes = bookTypeService.findAll();
        return RespJson.pack(200,"",bookTypes);
    }

    //点赞加1
    @RequestMapping("/addRate/{bookid}")
    @ResponseBody
    public Map<String,Object> addRate(@PathVariable("bookid")Integer id){
        logger.info("bookid===="+id);
        bookService.addRate(id,1);//点赞加1
        return RespJson.pack(200,"点赞成功","");
    }

    //获得点赞前5的商品
    @RequestMapping("/book/findRate5")
    @ResponseBody
    public Map<String,Object> findRate5(){
        List<Book> books = bookService.findRate5();
        return RespJson.pack(200,"",books);
    }

    //加入到购物车前5的商品
    @RequestMapping("/book/findFav5")
    public Map<String,Object> findFav5(){
        List<Book> books = bookService.findFav5();
        return RespJson.pack(200,"",books);
    }

    //查找销售前5的商品
    @RequestMapping("/book/findSale5")
    @ResponseBody
    public Map<String,Object> findSale5(){
        List<Book> books = bookService.findSale5();
        return RespJson.pack(200,"",books);
    }

    //根据点赞数排序且可以分类按分页查询商品
    @RequestMapping("/findBookByPageRate/{start}/{num}/{typeid}")
    @ResponseBody
    public Map<String,Object> findBookByPageRate(@PathVariable("start")Integer start,
                                                 @PathVariable("num")Integer num,
                                                 @PathVariable("typeid")Integer typeid){
        List<Book> books = bookService.findBookByPageRate(typeid, start - 1, num);
        return RespJson.pack(200,"",books);
    }

    //根据销售量排序且可以分类按分页查询商品
    @RequestMapping("/findBookByPageSale/{start}/{num}/{typeid}")
    @ResponseBody
    public Map<String,Object> findBookByPageSale(@PathVariable("start")Integer start,
                                                 @PathVariable("num")Integer num,
                                                 @PathVariable("typeid")Integer typeid){
        List<Book> books = bookService.findBookByPageSale(typeid, start - 1, num);
        return RespJson.pack(200,"",books);
    }

    //根据销售数排序且可以分类按分页查询商品
    @RequestMapping("/findBookByPageFav/{start}/{num}/{typeid}")
    @ResponseBody
    public Map<String,Object> findBookByPageFav(@PathVariable("start")Integer start,
                                                 @PathVariable("num")Integer num,
                                                 @PathVariable("typeid")Integer typeid){
        List<Book> books = bookService.findBookByPageSale(typeid, start - 1, num);
        return RespJson.pack(200,"",books);
    }


}
